package com.luom.fsp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.afterSalesService.AfterSalesServiceAddRequest;
import com.luom.fsp.model.dto.afterSalesService.AfterSalesServiceEditRequest;
import com.luom.fsp.model.dto.afterSalesService.AfterSalesServiceQueryRequest;
import com.luom.fsp.model.dto.afterSalesService.AfterSalesServiceUpdateRequest;
import com.luom.fsp.model.entity.AfterSalesService;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.AfterSalesServiceVO;
import com.luom.fsp.service.AfterSalesServiceService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 售后服务接口
 *
*/
@RestController
@RequestMapping("/afterSalesService")
@Slf4j
public class AfterSalesServiceController {

    @Resource
    private AfterSalesServiceService afterSalesServiceService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建售后服务
     *
     * @param afterSalesServiceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addAfterSalesService(@RequestBody AfterSalesServiceAddRequest afterSalesServiceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(afterSalesServiceAddRequest == null, ErrorCode.PARAMS_ERROR);
        AfterSalesService afterSalesService = new AfterSalesService();
        BeanUtils.copyProperties(afterSalesServiceAddRequest, afterSalesService);

        // 返回新写入的数据 id
        long newAfterSalesServiceId = afterSalesServiceService.addAfterSalesService(afterSalesService, request);
        return ResultUtils.success(newAfterSalesServiceId);
    }

    /**
     * 删除售后服务
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteAfterSalesService(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        afterSalesServiceService.deleteAfterSalesService(deleteRequest.getId(), request);
        return ResultUtils.success(true);
    }

    /**
     * 取消售后服务
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/cancel")
    public BaseResponse<Boolean> cancelAfterSalesService(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        afterSalesServiceService.cancelAfterSalesService(deleteRequest.getId(), request);
        return ResultUtils.success(true);
    }

    /**
     * 更新售后服务（仅管理员可用）
     *
     * @param afterSalesServiceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAfterSalesService(@RequestBody AfterSalesServiceUpdateRequest afterSalesServiceUpdateRequest) {
        if (afterSalesServiceUpdateRequest == null || afterSalesServiceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AfterSalesService afterSalesService = new AfterSalesService();
        BeanUtils.copyProperties(afterSalesServiceUpdateRequest, afterSalesService);
        // 数据校验
        afterSalesServiceService.validAfterSalesService(afterSalesService, false);
        // 判断是否存在
        long id = afterSalesServiceUpdateRequest.getId();
        AfterSalesService oldAfterSalesService = afterSalesServiceService.getById(id);
        ThrowUtils.throwIf(oldAfterSalesService == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = afterSalesServiceService.updateById(afterSalesService);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取售后服务（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<AfterSalesServiceVO> getAfterSalesServiceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        AfterSalesService afterSalesService = afterSalesServiceService.getById(id);
        ThrowUtils.throwIf(afterSalesService == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(afterSalesServiceService.getAfterSalesServiceVO(afterSalesService, request));
    }

    /**
     * 分页获取售后服务列表（仅管理员可用）
     *
     * @param afterSalesServiceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AfterSalesService>> listAfterSalesServiceByPage(@RequestBody AfterSalesServiceQueryRequest afterSalesServiceQueryRequest) {
        long current = afterSalesServiceQueryRequest.getCurrent();
        long size = afterSalesServiceQueryRequest.getPageSize();
        // 查询数据库
        Page<AfterSalesService> afterSalesServicePage = afterSalesServiceService.page(new Page<>(current, size),
                afterSalesServiceService.getQueryWrapper(afterSalesServiceQueryRequest));
        return ResultUtils.success(afterSalesServicePage);
    }

    /**
     * 分页获取售后服务列表（封装类）
     *
     * @param afterSalesServiceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<AfterSalesServiceVO>> listAfterSalesServiceVOByPage(@RequestBody AfterSalesServiceQueryRequest afterSalesServiceQueryRequest,
                                                               HttpServletRequest request) {
        long current = afterSalesServiceQueryRequest.getCurrent();
        long size = afterSalesServiceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<AfterSalesService> afterSalesServicePage = afterSalesServiceService.page(new Page<>(current, size),
                afterSalesServiceService.getQueryWrapper(afterSalesServiceQueryRequest));
        // 获取封装类
        return ResultUtils.success(afterSalesServiceService.getAfterSalesServiceVOPage(afterSalesServicePage, request));
    }

    /**
     * 分页获取当前登录用户创建的售后服务列表
     *
     * @param afterSalesServiceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<AfterSalesServiceVO>> listMyAfterSalesServiceVOByPage(@RequestBody AfterSalesServiceQueryRequest afterSalesServiceQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(afterSalesServiceQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        afterSalesServiceQueryRequest.setUserId(loginUser.getId());
        long current = afterSalesServiceQueryRequest.getCurrent();
        long size = afterSalesServiceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<AfterSalesService> afterSalesServicePage = afterSalesServiceService.page(new Page<>(current, size),
                afterSalesServiceService.getQueryWrapper(afterSalesServiceQueryRequest));
        // 获取封装类
        return ResultUtils.success(afterSalesServiceService.getAfterSalesServiceVOPage(afterSalesServicePage, request));
    }

    /**
     * 编辑售后服务（给用户使用）
     *
     * @param afterSalesServiceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editAfterSalesService(@RequestBody AfterSalesServiceEditRequest afterSalesServiceEditRequest, HttpServletRequest request) {
        if (afterSalesServiceEditRequest == null || afterSalesServiceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AfterSalesService afterSalesService = new AfterSalesService();
        BeanUtils.copyProperties(afterSalesServiceEditRequest, afterSalesService);
        // 数据校验
        afterSalesServiceService.validAfterSalesService(afterSalesService, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = afterSalesServiceEditRequest.getId();
        AfterSalesService oldAfterSalesService = afterSalesServiceService.getById(id);
        ThrowUtils.throwIf(oldAfterSalesService == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldAfterSalesService.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = afterSalesServiceService.updateById(afterSalesService);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
